package com.loongair.gjmobile;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.CallSuper;
import androidx.annotation.Nullable;
import com.facebook.react.ReactActivity;
import android.util.Log;
import android.widget.ImageView;

//import cn.org.bjca.anysign.android.R3.api.exceptions.CrashHandler;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import cn.org.bjca.anysign.android.api.Interface.OnSignatureResultListener;
//import cn.org.bjca.anysign.android.api.R;
import cn.org.bjca.anysign.android.api.core.BatchSignatureObj;
import cn.org.bjca.anysign.android.api.core.CachetObj;
import cn.org.bjca.anysign.android.api.core.CommentObj;
import cn.org.bjca.anysign.android.api.core.OriginalContent;
import cn.org.bjca.anysign.android.api.core.SignRule;
import cn.org.bjca.anysign.android.api.core.SignRule.KWRule;
import cn.org.bjca.anysign.android.api.core.SignRule.SignRuleType;
import cn.org.bjca.anysign.android.api.core.SignRule.XYZRule;
import cn.org.bjca.anysign.android.api.core.SignatureAPI;
import cn.org.bjca.anysign.android.api.core.SignatureObj;
import cn.org.bjca.anysign.android.api.core.Signer;
import cn.org.bjca.anysign.android.api.core.Signer.SignerCardType;
import cn.org.bjca.anysign.android.api.core.domain.AnySignBuild;
import cn.org.bjca.anysign.android.api.core.domain.BJCAAnySignAVType;
import cn.org.bjca.anysign.android.api.core.domain.BioType;
import cn.org.bjca.anysign.android.api.core.domain.CommentInputType;
import cn.org.bjca.anysign.android.api.core.domain.DataType;
import cn.org.bjca.anysign.android.api.core.domain.OriginalContentType;
import cn.org.bjca.anysign.android.api.core.domain.SignResult;
import cn.org.bjca.anysign.android.api.core.domain.SignatureType;
import cn.org.bjca.anysign.core.domain.BJCASignatureBoardType;

public final class SignatureViewActivity extends ReactActivity {
    private SignatureAPI api;
    @Override
    @CallSuper
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String contentBusinessId = "m2303";
        try {
            AnySignBuild.Default_Cert_EncAlg = "RSA"; // 设置签名算法，默认为RSA，可以设置成SM2
            AnySignBuild.privacyTold = true; //所有签名提示隐私协议

            api = new SignatureAPI(this);

            // 所有api接口中设置成功返回 SignatureAPI.SUCCESS（0），其他错误
            int apiResult = api.setChannel("999999");
            if(apiResult == SignatureAPI.SUCCESS){
                Log.e("XSS", "apiResult -- setChannel：成功");
            }else{
                Log.e("XSS", "apiResult -- setChannel：失败");
            }
            InputStream is = this.getResources().openRawResource(R.raw.test_pdf);
            byte[] bTemplate = new byte[is.available()];
            is.read(bTemplate);

            /**
             * 配置此次签名对应的模板数据
             * 参数1：表示模板类型，不可为空：如果为PDF和HTML格式，调用下面构造函数
             *        ContextID.FORMDATA_PDF：PDF格式，ContextID.FORMDATA_HTML：HTML格式
             * 参数2：表示模板数据byte数组类型，不可为空
             * 参数3：业务流水号/工单号，不可为空
             */
            apiResult = api.setOrigialContent(new OriginalContent(OriginalContentType.CONTENT_TYPE_PDF, bTemplate,  contentBusinessId));
            Log.e("XSS", "apiResult -- setOrigialContent：" + apiResult);
            //			 实例化签名规则
			//SignRule signRule1 = SignRule.getInstance(SignRule.SignRuleType.TYPE_KEY_WORD);
            //signRule1.setKWRule(new SignRule.KWRule("电子邮箱:", 10, 10, 1, 1));
			//SignRule signRule2 = SignRule.getInstance(SignRule.SignRuleType.TYPE_KEY_WORD);
            //signRule2.setKWRule(new SignRule.KWRule("甲方（用户）:", 10, 10, 1, 1));
			//SignRule signRule3 = SignRule.getInstance(SignRule.SignRuleType.TYPE_KEY_WORD);
            //signRule3.setKWRule(new SignRule.KWRule("申请人/经办人", 10, 10, 1, 1));
            SignRule signRule1 = SignRule.getInstance(SignRuleType.TYPE_XYZ);
            signRule1.setXYZRule(new XYZRule(84, 523, 200, 411, 0,"dp"));
            SignRule signRule2 = SignRule.getInstance(SignRuleType.TYPE_XYZ);
            signRule2.setXYZRule(new XYZRule(44, 332, 200, 223, 0,"dp"));
            SignRule signRule3 = SignRule.getInstance(SignRuleType.TYPE_XYZ);
            signRule3.setXYZRule(new XYZRule(0, 110, 200, 10, 0,"dp"));
            List<SignRule> signRules = new ArrayList<>();
            signRules.add(signRule1);
            signRules.add(signRule2);
            signRules.add(signRule3);
            Signer signer = new Signer("绍坎", "222", Signer.SignerCardType.TYPE_IDENTITY_CARD);
//			实例化手写签名对象
//			参数1：手写签名对象索引值
            BatchSignatureObj obj = new BatchSignatureObj(0,signRules,signer);

            //Signer signer = new Signer("李白", "111", SignerCardType.TYPE_IDENTITY_CARD);
            ////  实例化手写签名对象 参数1：手写签名对象索引值；参数2：签名规则；参数3：签名人信息
            //SignatureObj obj = new SignatureObj(0,signRule,signer);
            obj.single_height = 100; //  设置签名图片高度，单位dip
            obj.single_width = 100; //   设置签名图片宽度，单位dip
            //  手写识别开关，true为开启手写识别，false为关闭手写识别
            obj.isdistinguish = false;
            //  识别错误的次数，超过识别错误个数时直接跳出识别，直接返回结果。默认为0时，一直走识别。此参数的前提是识别系统为true时
            obj.ocrErrorTime = 3;                
            //  签名是否必须,设置为true时必须进行签名，默认true
            obj.nessesary = false;
            //  设置签名笔迹颜色，默认为黑色
            obj.penColor = Color.RED;
            //  用钢笔/毛笔字模式,true为钢笔，false为毛笔
            obj.isNoBrushes = true;                
            //  签名笔迹大小
            obj.penSize = 15;
            //  需要显示在签名框顶栏的标题
            obj.title = "请李凤国签字";
            //  单字签名框中需要突出显示部分的起始位置和结束位置
            obj.titleSpanFromOffset = 1;
            //  单字签名框中需要突出显示部分的起始位置和结束位置
            obj.titleSpanToOffset = 3;
            //  识别错误提示语
            obj.distinguishErrorText = "识别错误";
            //  显示框的类型
            obj.signatureBoardType = BJCASignatureBoardType.BJCAAnySignWordNumberTransformType;

            ////  注册单签签名对象
            //apiResult = api.addSignatureObj(obj);
            //Log.e("XSS", "apiResult -- addSignatureObj：" + apiResult);
//			 注册单签签名对象
            apiResult = api.addBatchSignatureObj(obj);
            Log.e("XSS", "apiResult -- addSignatureObj：" + apiResult);
            apiResult = api.showSignatureDialog(0);// 弹出单签签名框签名
            Log.e("XSS", "apiResult -- showSignatureDialog：" + apiResult);
            /*
             * 注册签名结果回调函数
             */
            api.setOnSignatureResultListener(new OnSignatureResultListener() {

                @Override
                public void onSignResult(final SignResult signResult)
                {

                ArrayList<String> list = (ArrayList<String>)api.genSignRequest();
                if(list != null){
                    for (int i = 0; i < list.size(); i++) {
                        Log.e("XSS", "onSignResult genSignRequest: " + i + list.get(i));
                    }
                    //Toast.makeText(SignatureViewActivity.this,"打包成功",Toast.LENGTH_SHORT).show();
                }else{
                    //Toast.makeText(SignatureViewActivity.this,"打包失败",Toast.LENGTH_SHORT).show();
                        Log.e("XSS", "onSignResult genSignRequest: null");
                }
                    showImgPreviewDlg(signResult.signature);

                    if(signResult.eviPic != null && signResult.eviPic.length != 0){
                        runOnUiThread(new Runnable()
                        {
                            public void run()
                            {
                                Bitmap camera_pic = BitmapFactory.decodeByteArray(signResult.eviPic, 0, signResult.eviPic.length);
                                showImgPreviewDlg(camera_pic);

                            }
                        });
                    }

                    Log.e("XSS", "onSignResult signIndex : " + signResult.signIndex + "  resultCode : " + signResult.resultCode+ "  signType : " + signResult.signType
                            + "  eviPic : " + signResult.eviPic);

                }

                @Override
                public void onCancel(int index, SignatureType signType)
                {
                    Log.e("XSS", "onCancel index : " + index + "  signType : " + signType);

                }

                @Override
                public void onDismiss(int index, SignatureType signType)
                {
                    Log.e("XSS", "onDismiss index : " + index + "  signType : " + signType);
                }

            });
        } catch (Exception ex) {
            ex.printStackTrace();
        } 
    }
    private void showImgPreviewDlg(Bitmap img) {
        ImageView iv = new ImageView(this);
        iv.setBackgroundColor(Color.WHITE);
        iv.setImageBitmap(img);
        new AlertDialog.Builder(this).setView(iv).show();
    }
}
